package com.xinya.taobaosale.ui.presenter.impl;

import android.util.Log;

import com.xinya.taobaosale.model.ApiException;
import com.xinya.taobaosale.model.api.ApiHelper;
import com.xinya.taobaosale.model.domain.CategoryBean;
import com.xinya.taobaosale.model.domain.ResultBean;
import com.xinya.taobaosale.ui.presenter.interfaces.IHomeCallback;
import com.xinya.taobaosale.ui.presenter.interfaces.IHomePresenter;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ClassName: HomePresenterImpl$
 * @Description: java类作用描述
 * @Author: xinya
 * @CreateDate: 2021/2/1$ 19:52$
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class HomePresenterImpl implements IHomePresenter<IHomeCallback>{
    private static final String TAG = "HomePresenterImpl";

    @Override
    public void getCategories() {

        for (IHomeCallback callback : getCallbackList()) {
            callback.onLoading(-1);
        }

        ApiHelper.INST.mService.getCategories().enqueue(new Callback<ResultBean<List<CategoryBean>>>() {
            @Override
            public void onResponse(Call<ResultBean<List<CategoryBean>>> call,
                                   Response<ResultBean<List<CategoryBean>>> response) {
                ResultBean<List<CategoryBean>> resultBean = response.body();
                if (resultBean == null) {
                    for (IHomeCallback callback : getCallbackList()) {
                        callback.onLoadError(-1);
                    }
                    return;
                }
                try {
                    List<CategoryBean> categoryBeanList = resultBean.getData();

                    for (IHomeCallback callback : getCallbackList()) {
                        callback.onLoadSuccess(-1);
                        callback.onCategoriesLoaded(categoryBeanList);
                    }
                } catch (ApiException e) {
                    Log.e(TAG, "onResponse: " + e.getCode() + " --> " + e.getMessage());
                    for (IHomeCallback callback : getCallbackList()) {
                        callback.onLoadEmpty(-1);
                    }
                }

            }

            @Override
            public void onFailure(Call<ResultBean<List<CategoryBean>>> call, Throwable t) {
                for (IHomeCallback callback : getCallbackList()) {
                    callback.onLoadError(-1);
                }
            }
        });
    }

    private static List<IHomeCallback> callbackList = new ArrayList<>();

    public List<IHomeCallback> getCallbackList() {
        return callbackList;
    }

    public void register(IHomeCallback callback) {
        if (callbackList.contains(callback)) {
            return;
        }
        callbackList.add(callback);
    }

    public void unRegister(IHomeCallback callback) {
        callbackList.remove(callback);
    }
}
